<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"dttx123.gitee.io","root":"/blog/","scheme":"Gemini","version":"8.0.0-rc.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="ExpressExpress 框架 基于 Node.js 平台，快速、开放、极简的 web 开发框架 express 官网 express 中文网  起步 安装：npm i express  1234567891011121314&#x2F;&#x2F; 导入 expressvar express &#x3D; require(&#39;express&#39;)&#x2F;&#x2F; 创建 express实例，也就是创建 express服务器var app">
<meta property="og:type" content="article">
<meta property="og:title" content="express">
<meta property="og:url" content="http://dttx123.gitee.io/2018/07/07/nodejs/03-express%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Starry Night">
<meta property="og:description" content="ExpressExpress 框架 基于 Node.js 平台，快速、开放、极简的 web 开发框架 express 官网 express 中文网  起步 安装：npm i express  1234567891011121314&#x2F;&#x2F; 导入 expressvar express &#x3D; require(&#39;express&#39;)&#x2F;&#x2F; 创建 express实例，也就是创建 express服务器var app">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-07-06T16:00:00.000Z">
<meta property="article:modified_time" content="2020-05-13T03:34:47.286Z">
<meta property="article:author" content="大春哥">
<meta property="article:tag" content="express">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://dttx123.gitee.io/2018/07/07/nodejs/03-express%E7%AC%94%E8%AE%B0/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>express | Starry Night</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line toggle-line-first"></span>
        <span class="toggle-line toggle-line-middle"></span>
        <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Starry Night</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">这就朕为你打下的江山</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/07/07/nodejs/03-express%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          express
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-07-07 00:00:00" itemprop="dateCreated datePublished" datetime="2018-07-07T00:00:00+08:00">2018-07-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:34:47" itemprop="dateModified" datetime="2020-05-13T11:34:47+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="Express"><a href="#Express" class="headerlink" title="Express"></a>Express</h1><h2 id="Express-框架"><a href="#Express-框架" class="headerlink" title="Express 框架"></a>Express 框架</h2><ul>
<li><strong>基于 Node.js 平台，快速、开放、极简的 web 开发框架</strong></li>
<li><a href="http://expressjs.com/" target="_blank" rel="noopener">express 官网</a></li>
<li><a href="http://expressjs.com.cn/" target="_blank" rel="noopener">express 中文网</a></li>
</ul>
<h3 id="起步"><a href="#起步" class="headerlink" title="起步"></a>起步</h3><ul>
<li>安装：<code>npm i express</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入 express</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>)</span><br><span class="line"><span class="comment">// 创建 express实例，也就是创建 express服务器</span></span><br><span class="line"><span class="keyword">var</span> app = express()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 路由</span></span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'Hello World!'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 启动服务器</span></span><br><span class="line">app.listen(<span class="number">3000</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'服务器已启动'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="API说明"><a href="#API说明" class="headerlink" title="API说明"></a>API说明</h3><ul>
<li><code>express()</code>：创建一个Express应用，并返回，即：app</li>
<li><code>app.get()</code>：注册一个GET类型的路由<ul>
<li>注意：只要注册了路由，所有的请求都会被处理（未配置的请求路径，响应404）</li>
</ul>
</li>
<li><code>res.send()</code>：发送数据给客户端，并自动设置Content-Type<ul>
<li>参数可以是：字符串、数组、对象、Buffer</li>
<li>注意：只能使用一次</li>
</ul>
</li>
<li><code>req</code> 和 <code>res</code>：与http模块中的作用相同，是扩展后的请求和响应对象</li>
</ul>
<h2 id="注册路由"><a href="#注册路由" class="headerlink" title="注册路由"></a>注册路由</h2><ul>
<li>1 <code>app.METHOD</code>：比如：app.get / app.post / app.delete / app.patch</li>
<li>3 <code>app.use(path, callback)</code> 更重要的作用是处理中间件<ul>
<li>注意：只要是以path开头的请求地址，都可以被use处理</li>
<li>注意：可以处理任意的请求类型</li>
<li>注意：path参数可省略，默认值为：<code>/</code></li>
</ul>
</li>
</ul>
<h2 id="实现静态服务器"><a href="#实现静态服务器" class="headerlink" title="实现静态服务器"></a>实现静态服务器</h2><ul>
<li><code>req.path</code>：请求路径<ul>
<li>示例：URL为’example.com/users?sort=desc’，path表示：<code>/users</code></li>
</ul>
</li>
<li><code>res.sendFile()</code></li>
</ul>
<h3 id="处理静态资源"><a href="#处理静态资源" class="headerlink" title="处理静态资源"></a>处理静态资源</h3><ul>
<li>静态资源：图片、CSS、JavaScript 文件 等</li>
<li>如何处理？使用 express.static() 方法来托管静态资源</li>
<li>注意：<code>express.static()</code>可以调用多次</li>
<li>思考：<code>app.use(&#39;/web&#39;, express.static(&#39;web&#39;))</code> 的含义？<ul>
<li>访问：<code>http://localhost:3000/web/anoceanofsky.jpg</code></li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 托管web目录下的静态资源</span></span><br><span class="line">app.use(express.static(<span class="string">'web'</span>))</span><br><span class="line"><span class="comment">// 相当于：app.use('/', express.static('web'))</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 访问上述静态资源</span></span><br><span class="line"><span class="comment">// http://localhost:3000/anoceanofsky.jpg</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 当请求达到服务器后，express就会到web目录下，查找anoceanofsky.jpg</span></span><br><span class="line"><span class="comment">// 并读取该文件，返回给浏览器</span></span><br></pre></td></tr></table></figure>

<h2 id="request常用属性和方法"><a href="#request常用属性和方法" class="headerlink" title="request常用属性和方法"></a>request常用属性和方法</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取请求路基中的参数，是一个对象 ---&gt; Get请求参数</span></span><br><span class="line">req.query</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取POST请求参数，需要配置`body-parser`模块， POST请求参数</span></span><br><span class="line">req.body</span><br></pre></td></tr></table></figure>

<ul>
<li>获取<code>POST</code>请求参数</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入body-parser模块</span></span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line"><span class="comment">// 将POST请求参数转化为对象，存储到req.body中</span></span><br><span class="line">app.use(bodyParser.urlencoded(&#123; <span class="attr">extended</span>: <span class="literal">true</span> &#125;)); <span class="comment">// for parsing application/x-www-form-urlencoded</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 此时，就可以获取到POST请求参数了</span></span><br><span class="line"><span class="built_in">console</span>.log(req.body)</span><br></pre></td></tr></table></figure>

<h2 id="response常用属性和方法"><a href="#response常用属性和方法" class="headerlink" title="response常用属性和方法"></a>response常用属性和方法</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// send() 发送数据给客户端，并自动设置Content-Type</span></span><br><span class="line">res.send()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发送文件给浏览器，并根据文件后缀名自动设置Content-Type</span></span><br><span class="line"><span class="comment">// 注意：文件路径必须是绝对路径</span></span><br><span class="line">res.sendFile(path.join(__dirname, <span class="string">'index.html'</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">// 设置HTTP响应码</span></span><br><span class="line">res.status(<span class="number">200</span>)</span><br><span class="line"><span class="comment">// 设置响应头</span></span><br><span class="line">res.set(<span class="string">'Content-Type'</span>, <span class="string">'text/plain'</span>)</span><br><span class="line">res.set(&#123;</span><br><span class="line">  <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>,</span><br><span class="line">  <span class="string">'cute'</span>: <span class="string">'fangfang'</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重定向</span></span><br><span class="line">res.redirect(<span class="string">'/index'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="Express使用模板引擎"><a href="#Express使用模板引擎" class="headerlink" title="Express使用模板引擎"></a>Express使用模板引擎</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 为后缀为html的模板设置模板引擎</span></span><br><span class="line">app.engine(<span class="string">'html'</span>, <span class="built_in">require</span>(<span class="string">'express-art-template'</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">// 设置模板文件所在的目录</span></span><br><span class="line">app.set(<span class="string">'views'</span>, <span class="string">'./'</span>)</span><br><span class="line"><span class="comment">// 设置模板文件的后缀为 html</span></span><br><span class="line">app.set(<span class="string">'view engine'</span>, <span class="string">'html'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 渲染 index.html 模板文件，并发送给浏览器</span></span><br><span class="line">res.render(<span class="string">'index'</span>, &#123; <span class="attr">list</span>: [] &#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Express-中外置路由使用"><a href="#Express-中外置路由使用" class="headerlink" title="Express 中外置路由使用"></a>Express 中外置路由使用</h2><ul>
<li>目的：将路由封装到一个独立的路由模块中，有利于代码的封装和模块化</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  router.js 文件代码如下:</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1 加载 express 模块</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2 调用 express.Router() 方法，得到一个路由容器实例</span></span><br><span class="line"><span class="keyword">var</span> router = express.Router()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3 为 router 添加不同的路由</span></span><br><span class="line">router.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'hello express'</span>)</span><br><span class="line">&#125;)</span><br><span class="line">router.get(<span class="string">'/add'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 4. 将 router 路由容器导出</span></span><br><span class="line"><span class="built_in">module</span>.exports = router</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  在 app.js 文件中：</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 1 加载上面自定义的路由模块</span></span><br><span class="line"><span class="keyword">var</span> router = <span class="built_in">require</span>(<span class="string">'./router'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> app = express()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2. 将自定义路由模块 router 通过 app.use() 方法挂载到 app 实例上</span></span><br><span class="line"><span class="comment">//    这样 app 实例程序就拥有了 router 的路由</span></span><br><span class="line">app.use( router )</span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">3000</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'running...'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="中间件"><a href="#中间件" class="headerlink" title="中间件"></a>中间件</h2><p><em>中间件（Middleware）</em> 是一个函数，它可以访问请求对象<code>req</code>, 响应对象<code>res</code>, 可以通过<code>next</code>参数将中间件传递给下一个中间件</p>
<p>中间件作用： 给req 和 res 拓展功能 </p>
<p>中间件的功能包括：</p>
<ul>
<li>执行任何代码。</li>
<li>修改请求和响应对象。</li>
<li>终结请求-响应循环。</li>
<li>调用堆栈中的下一个中间件。</li>
</ul>
<p>定义一个中间件</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//添加一个中间件</span></span><br><span class="line"><span class="comment">//中间件是啥：中间件就是一个函数，中间件可以访问到req和res，可以通过next发送给下一个中间件</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">req,res, next</span>) </span>&#123;</span><br><span class="line">  req.aa = <span class="string">"大春哥"</span>;</span><br><span class="line">  res.bb = <span class="string">"很帅"</span>;</span><br><span class="line">  <span class="comment">//中间件可以通过next传递给下一个中间件</span></span><br><span class="line">  next();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="body-parser中间件的使用"><a href="#body-parser中间件的使用" class="headerlink" title="body-parser中间件的使用"></a>body-parser中间件的使用</h2><ul>
<li>获取get请求的参数：<code>req.query</code></li>
<li>获取post请求的参数<code>req.body</code>，但是需要借助<code>body-parser</code>中间件</li>
</ul>
<p>安装：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install body-parser</span><br></pre></td></tr></table></figure>

<p>使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 导入body-parser中间件</span></span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line"><span class="comment">//使用body-parser中间件</span></span><br><span class="line"><span class="comment">//extended:true 表示使用qs库来解析查询字符串  extended：false表示使用querystring库来解析字符串</span></span><br><span class="line">app.use(bodyParser.urlencoded(&#123;<span class="attr">extended</span>:<span class="literal">false</span>&#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">//3. 通过req.body获取参数</span></span><br><span class="line">app.post(<span class="string">"/"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(req.body);</span><br><span class="line">  res.send(<span class="string">"哈哈"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>注意：中间件是有执行顺序的</strong></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/express/" rel="tag"># express</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/" rel="prev" title="模块化">
      <i class="fa fa-chevron-left"></i> 模块化
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/08/01/nodejs/04-mysq/" rel="next" title="sql 基础">
      sql 基础 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Express"><span class="nav-text">Express</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Express-框架"><span class="nav-text">Express 框架</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#起步"><span class="nav-text">起步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#API说明"><span class="nav-text">API说明</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注册路由"><span class="nav-text">注册路由</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现静态服务器"><span class="nav-text">实现静态服务器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#处理静态资源"><span class="nav-text">处理静态资源</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#request常用属性和方法"><span class="nav-text">request常用属性和方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#response常用属性和方法"><span class="nav-text">response常用属性和方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Express使用模板引擎"><span class="nav-text">Express使用模板引擎</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Express-中外置路由使用"><span class="nav-text">Express 中外置路由使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#中间件"><span class="nav-text">中间件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#body-parser中间件的使用"><span class="nav-text">body-parser中间件的使用</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="大春哥"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">大春哥</p>
  <div class="site-description" itemprop="description">IT</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">35</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">大春哥</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

</body>
</html>
